package koutei.stream;

import android.app.Activity;
import android.app.Dialog;
import android.view.Window;
import android.view.WindowManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.KeyEvent;
import android.widget.VideoView;
import android.widget.MediaController;
import android.widget.TextView;
import android.widget.Button;
import android.widget.Toast;
import android.widget.ProgressBar;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnErrorListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Bundle;
import android.net.Uri;
import android.content.Intent;
import android.content.DialogInterface;
import android.database.sqlite.SQLiteDoneException;
import android.util.Log;

public class SPlayer extends Activity{
    public final static String TAG = "SVP";
    public final static int BUFFERING_PROGRESS = 1;
    protected final static String retryingMessege = 
        "Retrying from source:                     \n";
    protected final static String bufferingMessege = 
        "Buffeirng from source:                    \n";
    private final static int SAVE_POS = 0;
    private StreamDB db;
    private Uri dataURI;
    private int pos;
    private String name;
    private VideoView videoView;
    private MenuItem savePosMenu;
    private Handler progressHandler;
    private BufferingDialog bufferingDialog;
    private boolean error;

    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        progressHandler = new Handler();
        db = new StreamDB(this);
        final Intent intent = getIntent();
        final String action = intent.getAction();
        Bundle extras = intent.getExtras();
        if(extras != null){
            name = extras.getString(db.NAME);
            pos = db.getBookmarkPos(name);
        }else{
            name = null;
            pos = 0;
        }
        dataURI = intent.getData();
        //Toast.makeText(this, dataURI.toString(), Toast.LENGTH_SHORT).show();
        Log.v(TAG, "VID:::"+dataURI.toString());
        if(Intent.ACTION_VIEW.equals(action)){
            setFullscreen();
            setContentView(R.layout.video);
            videoView = (VideoView) findViewById(R.video.videoView);
            MediaController mediaController = new MediaController(this, true);
            videoView.setMediaController(mediaController);
            mediaController.setAnchorView(videoView);
            videoView.setOnErrorListener(new MediaPlayer.OnErrorListener(){
                public boolean onError(MediaPlayer mp, int what, int extra){
                    setError();
                    bufferingDialog.setError();
                    return true;
                }
            });
            videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener(){
                public void onPrepared(MediaPlayer mp){
                    bufferingDialog.dismiss();
                }
            });
        }
        else{
            finish();
        }
    }

    public void onPause(){
        super.onPause();
        Log.v(TAG,"Pausing : !");
        db.close();
    }

    public void onResume(){
        super.onResume();
            db = new StreamDB(this);
        Log.v(TAG,"DB was closed?.."+!db.isOpen());
        String tmp = db.restoreUriState();
        Log.v(TAG,"Restoring : uri="+tmp);
        Log.v(TAG,"Restoring : isPlaying="+videoView.isPlaying());
        if(tmp!=null && videoView.isPlaying()==false){
            pos = db.restorePosState();
            dataURI = Uri.parse(tmp);
            name = db.restoreNameState();
            db.deleteState();
            Log.v(TAG,"Restoring : p="+pos+" name="+name);
        }
        if(videoView.isPlaying()==false){
            setVideo();
        }
        Log.v(TAG, "~~Name="+name);
    }

    public void onDestroy(){
        db.close();
        super.onDestroy();
    }

    public boolean onCreateOptionsMenu(Menu menu){
        savePosMenu=menu.add(0, SAVE_POS, 0, "Save Position");
        return true;
    }

    public boolean onPrepareOptionsMenu(Menu menu){
        Log.v(TAG, "~~name=null "+(name==null));
        if(name == null || name.equals("")){
            savePosMenu.setEnabled(false);
        }else{
            savePosMenu.setEnabled(true);
        }
        return true;
    }

    public boolean onOptionsItemSelected(MenuItem item){
        int itemId = item.getItemId();
        switch (itemId){
            case SAVE_POS:
                db.editBookmark(name, name, dataURI.toString(), 
                    videoView.getCurrentPosition());
                return true;
        }
        return false;
    }

    public void onSaveInstanceState(Bundle state){
        super.onSaveInstanceState(state);
        Log.v(TAG,"SaveInstance : isPlaying="+videoView.isPlaying()+" p="
            +videoView.getCurrentPosition());
        db.saveState(name, dataURI.toString(), videoView.getCurrentPosition());
        state.putString(db.URI, dataURI.toString());
        state.putInt(db.POS, videoView.getCurrentPosition());
        if(name != null){
            state.putString(db.NAME, name);
        }
    }

    public void onRestoreInstanceState(Bundle state){
        super.onRestoreInstanceState(state);
        Log.v(TAG,"RestoreInstance : isPlaying="+videoView.isPlaying()
            +" p="+videoView.getCurrentPosition());
        db.deleteState();
        dataURI = Uri.parse(state.getString(db.URI));
        pos = state.getInt(db.POS);
        if(state.containsKey(db.NAME)){
            name = state.getString(db.NAME);
        }
    }

    protected Dialog onCreateDialog(int id){
        switch(id){
            case BUFFERING_PROGRESS:
                BufferingDialog dialog = new BufferingDialog(this);
                dialog.setMessege(bufferingMessege+dataURI.toString());
                return dialog;
            default:
                return null;
        }
    }

    protected void onPrepareDialog(int id, Dialog d){
        switch(id){
            case BUFFERING_PROGRESS:
                bufferingDialog = (BufferingDialog) d;
                break;
            default:
                break;
        }
    }

    public void setVideo(){
        clearError();
        videoView.setVideoURI(dataURI);
        if(pos > 0){
            videoView.seekTo(pos);
        }
        showDialog(BUFFERING_PROGRESS);
        videoView.start();
    }

    public void setFullscreen(){
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }
   
    public void setNoTitle(){
        requestWindowFeature(Window.FEATURE_NO_TITLE);
    }

    public void updateBufferingDialog(final String messege){
        Log.v(TAG, "!!BufferingDialog->messege="+messege);
        progressHandler.post( new Runnable(){
            public void run(){
                bufferingDialog.setMessege(messege);
            }
        });
    }

    public void dismissBufferDialog(){
        progressHandler.post( new Runnable(){
            public void run(){
                dismissDialog(BUFFERING_PROGRESS);
            }
        });
    }

    public boolean hasError(){
        return error;
    }

    protected void setError(){
        error = true;
    }

    protected void clearError(){
        error = false;
    }

    public Uri getUri(){
        return dataURI;
    }

    public String getName(){
        return name;
    }

}

class BufferingDialog extends Dialog{
    private final TextView messege;
    private final SPlayer splayer;
    private final Button close;

    public BufferingDialog(SPlayer sp){
        super(sp);
        splayer = sp;
        setTitle("Buffering...");
        setContentView(R.layout.buffering_dialog);
        messege = (TextView) findViewById(R.buffering_dialog.messege);
        Button cancel = (Button) findViewById(R.buffering_dialog.cancel);
        close = (Button) findViewById(R.buffering_dialog.close);
        close.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v){
                dismiss();
            }
        });
        cancel.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v){
                dismiss();
                splayer.setError();
                splayer.finish();
            }
        });
        setOnKeyListener(new DialogInterface.OnKeyListener(){
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent e){
                Log.v(SPlayer.TAG, "key pressed"+KeyEvent.KEYCODE_BACK+
                    " ="+keyCode);
                if(splayer.hasError()){
                    if(e.getAction()==KeyEvent.ACTION_DOWN && 
                       keyCode==KeyEvent.KEYCODE_BACK){
                        dismiss();
                        splayer.finish();
                        return true;
                    }
                }
                return false;
            }
        });
    }


    public void setMessege(String text){
        messege.setText(text);
    }

    public String getMessege(){
        return messege.getText().toString();
    }
    
    public void setError(){
        setTitle("Error Playing Video");
        messege.setText("Error: Unable to play video\n"+
            splayer.getUri().toString());
        close.setText("Retry");
        close.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v){
                setTitle("Buffering...");
                String tmp = splayer.getUri().toString();
                messege.setText(SPlayer.retryingMessege+tmp+"\nBuffering..");
                splayer.setVideo();
            }
        });
    }
}

